package com.wangzhen.spring.ioc.dependcy.circular;

import com.wangzhen.spring.ioc.dependcy.entity.Student;
import com.wangzhen.spring.ioc.dependcy.entity.Teacher;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

import java.util.Arrays;

/**
 * Spring循环依赖演示，Student中依赖Teacher对象，Teacher对象中依赖Student对象
 * 1、teacher和student对象都是singleton对象的时候，才可以循环依赖成功
 * 2、teacher和student对象都是prototype对象的时候，循环依赖失败
 *
 * 总结：只有单例bean才能够循环依赖注入，protoptype类型的bean是不能够循环依赖注入的
 */
public class CircularDenpendcyDemo {

    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    @Bean
    public Student student() {
        Student student = new Student();
        student.setId(1);
        return student;
    }

    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    @Bean
    public Teacher teacher() {
        Teacher teacher = new Teacher();
        teacher.setName("zhangsan");
        return teacher;
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.setAllowCircularReferences(true);

        context.register(CircularDenpendcyDemo.class);

        context.refresh();

        System.out.println(context.getBean("student"));
        System.out.println(context.getBean("teacher"));
        Arrays.stream(context.getBeanFactory().getSingletonNames()).forEach(System.out::println);
        System.out.println();

        context.close();
    }
}
